<?php 
namespace App\Infra;

use DB;
use App\Models\Cases;
use App\Models\Front;
use App\Models\Rear;
use App\Utils\ModelOperatorUtil;

class CaseManager{

	use ModelOperatorUtil;

	public function getCaseFront($conditions){
		$cases = Cases::query()->with(['front','rear']);

		$cases->where('case_type',$conditions['case_type']);

		if(isset($conditions['start_age'])){
			$cases->where('age','>',$conditions['start_age'])->Where('age','<',$conditions['end_age']);
		}
		if(isset($conditions['start_weight'])){
			$cases->whereHas('front' , function($query) use($conditions){
				$query->where('weight','>',$conditions['start_weight'])->where('weight','<',$conditions['end_weight']);
			});
		}
		if(isset($conditions['start_bmi'])){
			$cases->whereHas('front' , function($query) use($conditions){
				$query->where('bmi','>',$conditions['start_bmi'])->where('bmi','<',$conditions['end_bmi']);
			});
		}
		if(isset($conditions['sex'])){
			$cases->where('sex',$conditions['sex']);
		}
		if(isset($conditions['province_id'])){
			$cases->where('province_id',$conditions['province_id']);
		}
		if(isset($conditions['history'])){
			$cases->where('history',$conditions['history']);
		}

		return $cases->orderBy("created_at",'DESC')->paginate(6);
	}

	public function getCases($conditions = null){

		$cases = Cases::query();

		if(isset($conditions['name']) && $conditions['name'] != ''){
			$cases->where('name','like','%'.$conditions['name'].'%');
		}
		if(isset($conditions['sex']) && $conditions['sex'] != ''){
			$cases->where('sex',$conditions['sex']);
		}
		if(isset($conditions['province_id']) && $conditions['province_id'] != ''){
			$cases->where('province_id',$conditions['province_id']);
		}
		if(isset($conditions['case_type']) && $conditions['case_type'] != ''){
			$cases->where('case_type',$conditions['case_type']);
		}

		$cases->orderBy('updated_at','desc');

		return $cases->paginate(10);
	}

	public function getCase($id){
		return Cases::with(['front','rear'])->find($id);
	}

	public function createCase($case,$front,$rear){
		DB::transaction(function() use($case,$front,$rear){

			$case = Cases::create($case);

			$front['case_id'] = $case->id;

			$rear['case_id'] = $case->id;

			Front::create($front);

			Rear::create($rear);
		});
	}

	public function updateCase($id,$case,$front,$rear){
		DB::transaction(function() use($id,$case,$front,$rear){

			$cases = Cases::find($id);

			$cases->update($case);

			$fronts = Front::where('case_id',$cases->id)->first();

			$fronts->update($front);

			$rears = Rear::where('case_id',$cases->id)->first();

			$rears->update($rear);
		});
	}

	public function deleteCase($id){

		$cases = Cases::find($id);

		$cases->delete();

		return $cases;
	}
}